package com.ainge.product.zk;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;


public class ServiceRegister {

    private static final String BASE_SERVICES = "/services";
    private static final String SERVICE_NAME = "/products";
    private static final String ipPort = "192.168.228.132:2181";

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void register(String address, int port) {
        try {
            ZooKeeper zooKeeper = new ZooKeeper(ipPort, 5000, (watchedEvent) -> {
                if (Watcher.Event.KeeperState.SyncConnected == watchedEvent.getState()) {
                    System.out.println(ipPort + "zkServer SyncConnected...");
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();
            Stat exists = zooKeeper.exists(BASE_SERVICES + SERVICE_NAME, false);
            if (exists == null) {
                if(zooKeeper.exists(BASE_SERVICES , false) == null){
                    zooKeeper.create(BASE_SERVICES, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
                zooKeeper.create(BASE_SERVICES + SERVICE_NAME, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            String server_path = address + ":" + port;
            zooKeeper.create(BASE_SERVICES + SERVICE_NAME + "/child", server_path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
